const { ipcMain } = require("electron");
const path = require("node:path");
const fs = require("fs");
const Datastore = require("node-persist");

const RootKey = "LOCAL-DATA-PLANB";

//默认数据格式及默认值
const DefaultData = {
	tomato: {
		time: 40, //番茄钟默认时间
		showCorner: true, //是否显示角标
		todayList: [], //今日番茄列表
	},
	coc: {
		labels: [], //组标签列表
		tasks: [], //计时任务
	},
};

//缓存所在文件夹
const CacheDirPath = path.join(
	process.env.LOCALAPPDATA || process.env.PROGRAMFILES,
	"PlantB",
	"data"
);

//获取数据
const getData = async (module) => {
	const storageData = await Datastore.get(RootKey);
	if (module) {
		//请求module的数据
		return storageData[module];
	}
	//请求全部数据
	return storageData;
};

//保存数据
const saveData = async (data, module) => {
	const storageData = await Datastore.get(RootKey);
	let finalData = undefined;
	if (module) {
		const preModuleData = storageData[module];
		const finalModuleData = Object.assign(preModuleData, data);
		storageData[module] = finalModuleData;
		finalData = storageData;
	} else {
		finalData = Object.assign(storageData, data);
	}
	await Datastore.set(RootKey, finalData);
};

module.exports = {
	async init() {
		//保证数据储存路径存在
		await initPath();
		//开始初始化
		await Datastore.init({
			dir: CacheDirPath,
		});
		await doDefaultValue();
		//添加IPC监听
		//同步：储存数据
		ipcMain.on("STORAGE-SAVE", async function (event, arg) {
			const { data, module } = arg;
			await saveData(data, module);
			event.returnValue = 1;
		});
		//同步：获取数据
		ipcMain.on("STORAGE-GET", async function (event, arg) {
			const { module } = arg;
			const value = await getData(module);
			event.returnValue = { module, value };
		});
	},
	getData,
	saveData,
};

//初始化Datastore路径
const initPath = () => {
	return new Promise((resolve, reject) => {
		fs.access(CacheDirPath, fs.constants.F_OK, (error) => {
			if (error) {
				//文件夹不存在
				fs.mkdir(CacheDirPath, { recursive: true }, (mkdirErr) => {
					if (mkdirErr) {
						reject("创建缓存文件夹失败:" + mkdirErr);
						return;
					}
					resolve();
				});
				return;
			}
			resolve();
		});
	});
};

//初始化默认数据
const doDefaultValue = async () => {
	const storageData = (await Datastore.get(RootKey)) ?? {};
	const finalData = Object.assign(DefaultData, storageData);
	await Datastore.set(RootKey, finalData);
};
